package org.jeecg.modules.demo.electriccharge.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.electriccharge.entity.ElectricCharge;
import org.jeecg.modules.demo.electriccharge.service.IElectricChargeService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.summary.entity.MonthlySummary;
import org.jeecg.modules.demo.summary.service.IMonthlySummaryService;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import static kotlin.reflect.jvm.internal.impl.builtins.StandardNames.FqNames.list;

/**
 * @Description: 电费
 * @Author: jeecg-boot
 * @Date:   2024-03-29
 * @Version: V1.0
 */
@Api(tags="电费")
@RestController
@RequestMapping("/electriccharge/electricCharge")
@Slf4j
public class ElectricChargeController extends JeecgController<ElectricCharge, IElectricChargeService> {
	@Autowired
	private IElectricChargeService electricChargeService;

	/**
	 * 分页列表查询
	 *
	 * @param electricCharge
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "电费-分页列表查询")
	@ApiOperation(value="电费-分页列表查询", notes="电费-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ElectricCharge>> queryPageList(ElectricCharge electricCharge,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ElectricCharge> queryWrapper = QueryGenerator.initQueryWrapper(electricCharge, req.getParameterMap());
		Page<ElectricCharge> page = new Page<ElectricCharge>(pageNo, pageSize);
		IPage<ElectricCharge> pageList = electricChargeService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param electricCharge
	 * @return
	 */
	@AutoLog(value = "电费-添加")
	@ApiOperation(value="电费-添加", notes="电费-添加")
	@RequiresPermissions("electriccharge:electric_charge:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ElectricCharge electricCharge) {
		electricChargeService.save(electricCharge);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param electricCharge
	 * @return
	 */
	@AutoLog(value = "电费-编辑")
	@ApiOperation(value="电费-编辑", notes="电费-编辑")
	@RequiresPermissions("electriccharge:electric_charge:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ElectricCharge electricCharge) {
		electricChargeService.updateById(electricCharge);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电费-通过id删除")
	@ApiOperation(value="电费-通过id删除", notes="电费-通过id删除")
	@RequiresPermissions("electriccharge:electric_charge:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		electricChargeService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "电费-批量删除")
	@ApiOperation(value="电费-批量删除", notes="电费-批量删除")
	@RequiresPermissions("electriccharge:electric_charge:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.electricChargeService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "电费-通过id查询")
	@ApiOperation(value="电费-通过id查询", notes="电费-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ElectricCharge> queryById(@RequestParam(name="id",required=true) String id) {
		ElectricCharge electricCharge = electricChargeService.getById(id);
		if(electricCharge==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(electricCharge);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param electricCharge
    */
    @RequiresPermissions("electriccharge:electric_charge:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ElectricCharge electricCharge) {
        return super.exportXls(request, electricCharge, ElectricCharge.class, "电费");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
	@Autowired
	private ISysDepartService departService;
	@Autowired
	private IMonthlySummaryService monthlySummaryService;
	@Autowired
	private ISysCategoryService sysCategoryService;

    @RequiresPermissions("electriccharge:electric_charge:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			//遍历
			try {
				//获取社区名称
				String departName = null;
				//获取起始到结束日期
				String qiShiDate = null;
				//判断社区名称是否一致
				List<ElectricCharge> checkList = ExcelImportUtil.importExcel(file.getInputStream(), ElectricCharge.class, params);
				//遍历
				// 创建一个 HashSet 来存储 departName，因为 HashSet 会自动去重
				Set<String> uniqueCommunityName = new HashSet<>();
				// 遍历 checkList，并将每个 electricCharge 的 departName 添加到 HashSet 中
				for (ElectricCharge electricCharge : checkList) {
					if (electricCharge.getCommunityName() != null) { // 确保 departName 不为 null
						uniqueCommunityName.add(electricCharge.getCommunityName());
					}
				}
				if (uniqueCommunityName.size() >1){
					return Result.OK("社区名称不一致");
				}else {
					Iterator<String> iterator = uniqueCommunityName.iterator();
					if (iterator.hasNext()) {
						departName = iterator.next();
					}
				}
				//判断是否存在社区名称
				QueryWrapper<SysDepart> departQueryWrapper = new QueryWrapper<>();
				departQueryWrapper.eq("depart_name",departName);
				List<SysDepart> sysDepartList = departService.list(departQueryWrapper);
				if (sysDepartList.isEmpty()){
					return Result.OK("此社区不存在");
				}
				//设置社区ID
				String departId = sysDepartList.get(0).getId();

				//获取账期月份
				String zhangMount = checkList.get(0).getZhangMonth();


				//获取账期ID,判断是否有账期ID
				QueryWrapper<MonthlySummary> summaryQueryWrapper = new QueryWrapper<>();
				summaryQueryWrapper
						.eq("community_id",departId)
						.eq("month",zhangMount);
				List<MonthlySummary> summaryList = monthlySummaryService.list(summaryQueryWrapper);
				if (summaryList.isEmpty()){
					return Result.OK("账期不存在!");
				}
				if (!(summaryList.get(0).getProgress().equals("0")||summaryList.get(0).getProgress().equals("6"))){
					return Result.OK("只允许导入账单进度为新建或审核有误调整中的账单！");
				}
				String zhangId = summaryList.get(0).getId();



				//判断是否已经导入过
				QueryWrapper<ElectricCharge> electricChargeQueryWrapper = new QueryWrapper<>();
				electricChargeQueryWrapper.eq("zhang_id",zhangId);
				List<ElectricCharge> nullList = electricChargeService.list(electricChargeQueryWrapper);
				//如果不为空 则对数据进行清空
				if (!nullList.isEmpty()){
					QueryWrapper<ElectricCharge> electricChargeQueryWrapperDelete = new QueryWrapper<>();
					electricChargeQueryWrapperDelete
							.eq("zhang_id",zhangId)
							.eq("create_type","2");
					electricChargeService.remove(electricChargeQueryWrapperDelete);
				}
				//清空后再进行保存
				List<ElectricCharge> list = ExcelImportUtil.importExcel(file.getInputStream(), ElectricCharge.class, params);
				List<ElectricCharge> chargeList = new ArrayList<>();

				//导入电费逻辑判断
				for (ElectricCharge electricCharge : list) {
					Date saleDate = electricCharge.getSaleDate();
					String zhangMonth = electricCharge.getZhangMonth();
					//获取起始日期
					Date date = DateUtil.parse(zhangMonth, DatePattern.NORM_MONTH_PATTERN);
					// 获取当月的第一天
					Date firstDayOfMonth = DateUtil.beginOfMonth(date);
					// 设置时间为当月的21号 0点0分0秒
					Date firstDate = DateUtil.offsetDay(firstDayOfMonth, 20);

					// 获取下个月的第一天
					Date firstDayOfNextMonth = DateUtil.offsetMonth(firstDayOfMonth, 1);
					// 获取下个月的第一天的前一秒
					Date lastSecondOfNextMonth = DateUtil.offsetSecond(DateUtil.beginOfMonth(firstDayOfNextMonth), -1);
					// 设置时间为下个月的20号23点59分59秒
					Date lastDate = DateUtil.offsetDay(lastSecondOfNextMonth, 20);

					//进行销售日期的筛选
					int starBiJiao = DateUtil.compare(saleDate,firstDate);
					int endBiJiao = DateUtil.compare(saleDate,lastDate);
					if (!((starBiJiao >=0) && (endBiJiao <= 0))){
						continue;
					}

					//设置缴费方式
					QueryWrapper<SysCategory> categoryQueryWrapper = new QueryWrapper<>();
					categoryQueryWrapper.eq("name",electricCharge.getPaymentWay());
					List<SysCategory> sysCategoryList = sysCategoryService.list(categoryQueryWrapper);
					String paymentWayId = sysCategoryList.get(0).getId();
					//设置缴费方式
					electricCharge.setPaymentWay(paymentWayId);
					//对账期ID进行赋值
					electricCharge.setZhangId(zhangId);
					//对社区id进行赋值
					electricCharge.setCommunityName(departId);
					//设置创建方式
					electricCharge.setCreateType("2");
					//将该对象添加到集合中
					chargeList.add(electricCharge);
				}
				//update-begin-author:taoyan date:20190528 for:批量插入数据
//                long start = System.currentTimeMillis();
				service.saveBatch(chargeList);
				//400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				//1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
//                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				//update-end-author:taoyan date:20190528 for:批量插入数据
				return Result.ok("文件导入成功！数据行数：" + chargeList.size());
			} catch (Exception e) {
				//update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
				String msg = e.getMessage();
				log.error(msg, e);
				if(msg!=null && msg.indexOf("Duplicate entry")>=0){
					return Result.error("文件导入失败:有重复数据！");
				}else{
					return Result.error("文件导入失败:" + e.getMessage());
				}
				//update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
//		return electricChargeService.importExcel(request,response);
//        return super.importExcel(request, response, ElectricCharge.class);
    }

}
